package com.inwavetech.os.util;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.inwavetech.os.entity.Os;
import com.inwavetech.os.entity.Product;
import com.inwavetech.os.entity.User;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DaoHelper extends OrmLiteSqliteOpenHelper {

    private static final String DATABASE_NAME = "com_inwavetech_os.db";
    private static final int DATABASE_VERSION = 1;

    public DaoHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    /**
     * This is called when the database is first created. Usually you should call createTable statements here to create
     * the tables that will store your data.
     */
    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
        try {
            Log.i(DaoHelper.class.getName(), "onCreate");

            TableUtils.createTable(connectionSource, Os.class);
            TableUtils.createTable(connectionSource, Product.class);
            TableUtils.createTable(connectionSource, User.class);
        } catch (SQLException e) {
            Log.e(DaoHelper.class.getName(), "Can't create database", e);

            throw new RuntimeException(e);
        }
    }

    @Override
    public <D extends Dao<T, ?>, T> D getDao(Class<T> clazz) {
        D dao = null;

        try {
            dao = super.getDao(clazz);
        } catch (SQLException e) {
            Log.e(DaoHelper.class.getName(), "It was not possible to get the oses due to a database error.");
        }

        return dao;
    }

    /**
     * This is called when your application is upgraded and it has a higher version number. This allows you to adjust
     * the various data to match the new version number.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {}

    /**
     * Close the database connections and clear any cached DAOs.
     */
    @Override
    public void close() {
        super.close();
    }
}
